package com.example.everying.utils;/*
 * 项目名称: everything
 * 文件名: WeChatPhoneNumberDecryptor
 * 作者: 张泽阳
 * 日期: 2025/5/15
 * 描述:
 */



import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;

public class WeChatPhoneNumberDecryptor {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    public static String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) throws Exception {
        try {


            // Base64 解码
            byte[] encryptedDataBytes = java.util.Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = java.util.Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = java.util.Base64.getDecoder().decode(iv);

            int base = 16;
            if (sessionKeyBytes.length % base != 0) {
                int groups = sessionKeyBytes.length / base + (sessionKeyBytes.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(sessionKeyBytes, 0, temp, 0, sessionKeyBytes.length);
                sessionKeyBytes = temp;
            }

            // 设置AES密钥和初始化向量
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            // 创建Cipher实例并初始化
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            // 解密
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

            // 将解密后的字节转换为字符串
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Base64解码失败: " + e.getMessage(),  e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("不支持AES算法", e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException("不支持PKCS5Padding", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的sessionKey", e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException("无效的IV参数", e);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("解密失败，请检查encryptedData是否完整", e);
        }
    }

    public static String decrypt(String encryptedData, String sessionKey, String iv) throws Exception {
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        byte[] keyByte = Base64.decodeBase64(sessionKey);
        byte[] ivByte = Base64.decodeBase64(iv);

        // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivByte);

        cipher.init(Cipher.DECRYPT_MODE, spec, paramSpec);

        byte[] resultByte = cipher.doFinal(dataByte);
        if (resultByte != null && resultByte.length > 0) {
            String result = new String(resultByte, StandardCharsets.UTF_8);
            return result;
        }
        return null;
    }



    public static void main(String[] args) {
        String encryptedData = "1RPRgf4THsQEscCEP5ixEbC+T/lyf5t5TaBi451jnvGnQScfGOUWAOnhGsN94oy3TRSgLEPfCbOBCCKo8F/XDZklVF4ltzih5aRFj74Fj7XW74Hpwr5JnjupoYBqXejJOhizz/AagNDp0932JBegn4VMMPOhpfQYhAIveRuaHqF54DRWuQil+FP5qgITuV14rm9bK2OftWIYfiIb52DbEA==";
        String sessionKey = "c+k064jppK0s6nRCbmCb5A==";
        String iv = "mOrIsbWu8arrir14L5PjcQ==";

//        String encryptedData = "zB4oD1i9/BVMh/nhP0qI6cUyxCpIykbnAkYxwSqyo1EkLER+AffUCVHYQAmmLq+1cgjlenIQMAezkErJDvBafm3WssQjZ0uqL3fMv6acMJrPwgkAH8eFK0aLuaAtmOCH4e+5m2rXVJ2sGgLFVOjtsaMrSh3GJ5nukLHT3oWqrRe2P45q9hOeTrRb10BoYtVLd+hjtIP9T5P/wnKZpmYsSw==";
//        String sessionKey = "8kxOB2Uhb6N6M2Wp+1qhXA==";
//        String iv = "qg3jEX03nSG94/mY/BPXkA==";

        try {
            String result = decryptPhoneNumber(encryptedData, sessionKey, iv);
            JSONObject obj = JSONObject.parseObject(result);
            String phoneNumber = obj.getString("phoneNumber");
            System.out.println("解密后的手机号：" + phoneNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

